package cn.edu.zjicm.wordsnet_d.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.PopupWindow.OnDismissListener;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.synchronize.HeadImageInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.PayInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.BitmapUtil;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.NightModeUtil;
import cn.edu.zjicm.wordsnet_d.util.StringUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.CircleImageView;

public class PersonalAccountActivity extends WordBaseActivity implements OnClickListener {

	public static final int TYPE_REGISTER = 0;
	public static final int TYPE_OTHER = 1;

	public static void startActivity(Context context, int type) {
		Intent i = new Intent(context, PersonalAccountActivity.class);
		i.putExtra("type", type);
		context.startActivity(i);
	}

	private RelativeLayout setAvatarButton, setNickNameButton, changePasswordButton, chooseSchoolButton, accountBtn, balanceLayout, rechargeLayout, consumeLayout, expLayout;
	private TextView nickName;
	private TextView account;
	private TextView school;
	private TextView addSchoolHint;
	private TextView beanTv;
	private TextView expTv;
	private CircleImageView avatar;
	private Button logout, finishBtn;
	private View mMask; // 弹出下载窗口时的遮罩
	private ViewFlipper btnFlipper;

	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESULT_REQUEST_CODE = 2;

	private String[] items = new String[] { "选择本地图片", "拍照" };
	private static final String IMAGE_FILE_NAME = "pic.jpg"; // 拍照默认图片名称
	private int type;
	private int padding;

	Handler syncBeforeLogoutHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(PersonalAccountActivity.this, null, "同步中...");
				break;
			case UserInterface.MSG_SUCCESS:
				Toast.makeText(PersonalAccountActivity.this, "同步成功", Toast.LENGTH_SHORT).show();
				logout();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(PersonalAccountActivity.this, "同步失败", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(PersonalAccountActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(PersonalAccountActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	Handler uploadHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(PersonalAccountActivity.this, null, "头像上传中...");
				break;
			case UserInterface.MSG_SUCCESS:
				setAvatar();
				Toast.makeText(PersonalAccountActivity.this, "头像上传成功", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(PersonalAccountActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(PersonalAccountActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(PersonalAccountActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WRONG_PHOTO:
				Toast.makeText(PersonalAccountActivity.this, "图像处理失败，请选择大小合适的图像", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		type = getIntent().getIntExtra("type", TYPE_OTHER);

		padding = Utils.changeDipToPx(this, 10);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		if (type == TYPE_REGISTER) {
			hideTitleBarBackButton();
			setTitleText("完善资料");
		} else {
			setTitleText("个人帐号");
		}
		setContentView(R.layout.activity_personalaccount);
		findViews();
		init();
	}

	private void findViews() {
		setAvatarButton = (RelativeLayout) findViewById(R.id.avatar_layout);
		setNickNameButton = (RelativeLayout) findViewById(R.id.nickname_layout);
		changePasswordButton = (RelativeLayout) findViewById(R.id.change_password);
		accountBtn = (RelativeLayout) findViewById(R.id.account_layout);
		nickName = (TextView) findViewById(R.id.nickname);
		account = (TextView) findViewById(R.id.account);
		avatar = (CircleImageView) findViewById(R.id.avatar);
		logout = (Button) findViewById(R.id.logout);
		mMask = findViewById(R.id.popupwindow_mask);
		chooseSchoolButton = (RelativeLayout) findViewById(R.id.school_layout);
		school = (TextView) findViewById(R.id.school);
		addSchoolHint = (TextView) findViewById(R.id.add_school_hint);
		btnFlipper = (ViewFlipper) findViewById(R.id.btn_flipper);
		finishBtn = (Button) findViewById(R.id.finish_btn);
		balanceLayout = (RelativeLayout) findViewById(R.id.balance_layout);
		rechargeLayout = (RelativeLayout) findViewById(R.id.recharge_layout);
		consumeLayout = (RelativeLayout) findViewById(R.id.consume_record_layout);
		beanTv = (TextView) findViewById(R.id.bean_tv);
		expLayout = (RelativeLayout) findViewById(R.id.exp_layout);
		expTv = (TextView) findViewById(R.id.exp_tv);
	}

	private void init() {
		if (type == TYPE_REGISTER) {
			balanceLayout.setVisibility(View.GONE);
			rechargeLayout.setVisibility(View.GONE);
			consumeLayout.setVisibility(View.GONE);
			expLayout.setVisibility(View.GONE);
			findViewById(R.id.personal_account_divider1).setVisibility(View.GONE);
			findViewById(R.id.personal_account_divider2).setVisibility(View.GONE);
			findViewById(R.id.personal_account_divider3).setVisibility(View.GONE);
			findViewById(R.id.personal_account_divider4).setVisibility(View.GONE);

			changePasswordButton.setVisibility(View.GONE);
			addSchoolHint.setVisibility(View.VISIBLE);
			accountBtn.setVisibility(View.GONE);
			findViewById(R.id.school_tv2).setVisibility(View.VISIBLE);
			if (NightModeUtil.isNightModeNow()) {
				chooseSchoolButton.setBackgroundResource(R.drawable.rectangle_half_bottom);
			} else {
				chooseSchoolButton.setBackgroundResource(R.drawable.setting_background_bottom_selector);
			}
			chooseSchoolButton.setPadding(0, padding, 0, padding);
			btnFlipper.setDisplayedChild(1);
		}

		setAvatarButton.setOnClickListener(this);
		setNickNameButton.setOnClickListener(this);
		changePasswordButton.setOnClickListener(this);
		chooseSchoolButton.setOnClickListener(this);
		logout.setOnClickListener(this);
		finishBtn.setOnClickListener(this);
		balanceLayout.setOnClickListener(this);
		rechargeLayout.setOnClickListener(this);
		consumeLayout.setOnClickListener(this);
		expLayout.setOnClickListener(this);

		setUserInfo();
		if (AppPreference.getWeChatUnionid(PersonalAccountActivity.this) != null) {
			changePasswordButton.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUserInfo();
	}

	private void setUserInfo() {
		String headPortraitURL = AppPreference.getHeadPortrait(PersonalAccountActivity.this);
		if (headPortraitURL != null) {
			Uri imageUri = Uri.parse(headPortraitURL);
			avatar.setImageURI(null);
			avatar.setImageURI(imageUri);
		}
		String nickNameStr = AppPreference.getNickName(PersonalAccountActivity.this);
		if (nickNameStr != null)
			nickName.setText(StringUtil.subString(nickNameStr, 12));
		String accountStr = AppPreference.getLoginID(PersonalAccountActivity.this);
		if (accountStr != null) {
			if (AppPreference.getWeChatUnionid(PersonalAccountActivity.this) != null) {
				accountStr = "微信 " + accountStr;
			}
			account.setText(accountStr);
		}
		// int schoolNameID =
		// AppPreference.getSchoolId(PersonalAccountActivity.this);
		// if (schoolNameID != -1) {
		// school.setText(WordFactory.getInstance(PersonalAccountActivity.this).getSchoolNameById(schoolNameID));
		// }
		String schoolName = AppPreference.getSchoolName(PersonalAccountActivity.this);
		if (schoolName != null) {
			school.setText(schoolName);
			// school.setText(StringUtil.subString(schoolName, 15));
		}

		beanTv.setText(WordFactory.getInstance(this).getZMD() + "");
		getUserWealth();

		expTv.setText(AppPreference.getEXP(PersonalAccountActivity.this) + "");
	}

	void getUserWealth() {
		// getProductListHandler.sendMessage(getProductListHandler.obtainMessage(UserInterface.MSG_START));
		PayInterface.getInstance(this).getUserWealth(getUserWealthHandler);
	}

	Handler getUserWealthHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UserInterface.MSG_START:
				break;
			case UserInterface.MSG_SUCCESS:
				beanTv.setText(WordFactory.getInstance(PersonalAccountActivity.this).getZMD() + "");
				break;
			case UserInterface.MSG_UNSUCCESS:
				// Toast.makeText(RechargeActivity.this, "获取商品信息失败，请稍后再试",
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				// Toast.makeText(RechargeActivity.this, "网络未连接，获取商品信息失败，请稍后再试",
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ERROR:
				// Toast.makeText(RechargeActivity.this, "网络未连接，获取商品信息失败，请稍后再试",
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				// Toast.makeText(RechargeActivity.this, "网络未连接，获取商品信息失败，请稍后再试",
				// Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		if (v == setAvatarButton) {
			showDialog();
		} else if (v == setNickNameButton) {
			ChangeNickNameActivity.startActivity(PersonalAccountActivity.this);
		} else if (v == changePasswordButton) {
			if (!UserInterface.getInstance(PersonalAccountActivity.this).isLogin()) {
				Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
			} else {
				ModifyPasswordActivity.startActivity(PersonalAccountActivity.this);
			}
		} else if (v == logout) {
			showLogoutCheckWindow();
		} else if (v == chooseSchoolButton) {
			AddSchoolActivity.startActivity(PersonalAccountActivity.this);
		} else if (v == finishBtn) {
			toNextActivity();
		} else if (v == balanceLayout) {
			ShowRegularActivity.startActivity(this, ShowRegularActivity.TYPE_BALANCE);
		} else if (v == rechargeLayout) {
			startActivity(new Intent(this, RechargeActivity.class));
		} else if (v == consumeLayout) {
			startActivity(new Intent(this, ConsumeRecordActivity.class));
		} else if (v == expLayout) {
			ShowRegularActivity.startActivity(PersonalAccountActivity.this, ShowRegularActivity.TYPE_EXPERIENCE_NUM2);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case IMAGE_REQUEST_CODE:
			if (data != null)
				startPhotoZoom(data.getData());
			break;
		case CAMERA_REQUEST_CODE:
			if (resultCode != 0) {
				File tempFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/" + IMAGE_FILE_NAME);
				Log.d("Test", "tempFile: " + tempFile.getPath());
				startPhotoZoom(Uri.fromFile(tempFile));
			}
			break;
		case RESULT_REQUEST_CODE:
			if (data != null) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					photo = extras.getParcelable("data");
					updateImage(photo); // 上传头像
				}
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void showDialog() {
		new AlertDialog.Builder(PersonalAccountActivity.this).setTitle("设置头像").setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*");
					intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
					break;
				case 1:
					Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
					File file = new File(path, IMAGE_FILE_NAME);
					intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
					startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
					break;
				}
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).show();

	}

	public void startPhotoZoom(Uri uri) {
		Log.d("Test", "startPhotoZoom:" + uri);
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
		int size = list.size();
		if (size == 0) {
			Bitmap btOriginal = null;
			try {
				btOriginal = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (btOriginal != null) {
				photo = BitmapUtil.CropForAvatar(btOriginal, PersonalAccountActivity.this);
				updateImage(photo); // 上传头像
			}
		} else {
			// 设置裁剪
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 320);
			intent.putExtra("outputY", 320);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, RESULT_REQUEST_CODE);
		}
	}

	Bitmap photo = null;

	private void updateImage(Bitmap photo) {
		uploadHandler.sendMessage(uploadHandler.obtainMessage(UserInterface.MSG_START));
		HeadImageInterface.getInstance(PersonalAccountActivity.this).upload(photo, uploadHandler);
	}

	private void setAvatar() {
		BitmapUtil.saveHeadPortrait(photo, PersonalAccountActivity.this);
		avatar.setImageBitmap(photo);
	}

	private PopupWindow mLogoutCheckWindow;

	private void showLogoutCheckWindow() {
		View view = View.inflate(this, R.layout.window_check_logout, null);
		if (mLogoutCheckWindow == null) {
			// init PopWindow cotentview
			LinearLayout logoutWithSyncButton = (LinearLayout) view.findViewById(R.id.logout_with_sync_confirm_button);
			LinearLayout logoutWithoutSyncButton = (LinearLayout) view.findViewById(R.id.logout_without_sync_confirm_button);
			TextView cancleButton = (TextView) view.findViewById(R.id.logout_cancle_button);
			logoutWithSyncButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mLogoutCheckWindow.dismiss();
					mLogoutCheckWindow = null;
					syncBeforeLogout();

					// 同步接口已上传exp，不再调用setExp接口
					// if(AppPreference.getEXPUpdated(PersonalAccountActivity.this)
					// == false)
					// ExpInterface.getInstance(PersonalAccountActivity.this).setExp();
				}
			});
			logoutWithoutSyncButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mLogoutCheckWindow.dismiss();
					mLogoutCheckWindow = null;
					logout();
				}
			});
			cancleButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mLogoutCheckWindow.dismiss();
					mLogoutCheckWindow = null;
				}
			});
			mLogoutCheckWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			mLogoutCheckWindow.setFocusable(true);
			mLogoutCheckWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.transparent_bg_drawable));
			mLogoutCheckWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mMask.setVisibility(View.GONE);
				}
			});
		}
		mMask.setVisibility(View.VISIBLE);
		mLogoutCheckWindow.showAtLocation(mMask, Gravity.CENTER, 0, 0);
	}

	private void logout() {
		String oldLoginID = AppPreference.getLoginID(PersonalAccountActivity.this);
		if (AppPreference.getWeChatUnionid(PersonalAccountActivity.this) != null) // 如果用户是用微信账号登录，退出后oldLoginID设为空
			oldLoginID = "";
		UserInterface.getInstance(PersonalAccountActivity.this).logout();
		LoginActivity.startActivity(PersonalAccountActivity.this, true, oldLoginID);
		finish();
	}

	private void syncBeforeLogout() {
		syncBeforeLogoutHandler.sendMessage(syncBeforeLogoutHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(PersonalAccountActivity.this).sync(syncBeforeLogoutHandler);
	}

	private void toNextActivity() {
		finish();
		if (AppPreference.hasStudyingBook(this))
			MainActivity.startActivity(PersonalAccountActivity.this);
		else
			SelectBookActivity.mStartActivity(PersonalAccountActivity.this, StaticData.MODE_INIT);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (type == TYPE_REGISTER) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				toNextActivity();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

}
